<!-- 查看详情  -->
<script setup lang='ts'>
import type { VxeGridInstance, VxeGridListeners } from 'vxe-table'

import { useContractGetEAuthLink } from '@fl/api/anjutong'
import { getNewCompanyOrgDetail, getSubDpt } from '@fl/api/iam-api'
import ButtonItem from '@fl/components/button-item.vue'
import { useAesDecrypt } from '@fl/hooks/web/useCrypt'
import { ElButton, ElCard, ElCol, ElForm, ElFormItem, ElRow } from 'element-plus'
import { cloneDeep } from 'lodash-es'
import { ref, toRefs, watch } from 'vue'
import { useRouter } from 'vue-router'

import { useDicts } from '../hooks/use-dicts'
import { useTable } from './hooks/use-table'
import viewItem from './view.vue'

const props = withDefaults(defineProps<{
    modelValue: boolean
    showId?: string
}>(), {

})

const emits = defineEmits(['update:modelValue', 'confirm'])

const { useDict } = useDicts()
const router = useRouter()
const isLoading = ref(true)

const { showId } = toRefs(props)
const initialDetail = {
    areaCode: '',
    areaName: '',
    businessLicense: '',
    catName: '',
    catType: '',
    contractFlag: undefined,
    contractPlat: undefined,
    cooperationType: '',
    email: '',
    enterpriseAccount: '',
    enterpriseId: '',
    enterpriseLevel: '',
    enterpriseLevelId: '',
    enterpriseName: '',
    enterpriseObjectID: '',
    enterpriseShort: '',
    enterpriseTypeName: '',
    establishmenDate: '',
    id: '',
    idCard: '',
    legalCard: '',
    legalCardBack: '',
    legalCardFront: '',
    legalRepresentative: '',
    parentId: '',
    parentName: '',
    phonenumber: '',
    registeredAddress: '',
    registeredMobile: '',
    status: '',
    unifiedSocialCreditCode: '',
    userName: '',
}
const detail = ref(cloneDeep(initialDetail))

// 发送e签宝授权链接
const { isPending, mutate } = useContractGetEAuthLink()

let subData = reactive<any>({})
const { btns, gridOptions } = useTable()
const xGrid = ref<VxeGridInstance<any>>()
const show = ref(false)

const gridEvents: VxeGridListeners<any> = {
    pageChange({ currentPage, pageSize }) {
        if (gridOptions.pagerConfig) {
            gridOptions.pagerConfig.currentPage = currentPage
            gridOptions.pagerConfig.pageSize = pageSize
        }
        getSubData()
    },
}

async function getSubData() {
    // console.log('获取下级', detail.value)
    if (!detail.value?.enterpriseObjectID)
        return
    gridOptions.loading = true
    getSubDpt({
        enterpriseObjectID: detail.value.enterpriseObjectID,
        parentId: detail.value.enterpriseId,
    }).then((res) => {
        if (res.code === 200) {
            console.log('获取下级企业', res)
            gridOptions.data = res.data ?? []
        }
    }).finally(() => {
        gridOptions.loading = false
    })
}

function onSubmit() {
    router.push(`edit-enterprise?id=${detail.value.id}`)
}

async function doAction(item: any, row: any) {
    switch (item.value) {
        case 'edit':
        case 'view':
        case 'delet':
            show.value = true
            subData = cloneDeep(row)
            break
        default:
            break
    }
}

function goToList() {
    emits('update:modelValue', true)
}

// 发起e签宝授权链接
function emitEAuth() {
    console.log('detail', detail.value)
    const params = {
        address: detail.value.registeredAddress,
        legalPersonCredentialsNumber: detail.value.legalCard,
        legalPersonName: detail.value.legalRepresentative,
        name: detail.value.enterpriseName,
        phone: detail.value.registeredMobile,
        s2ObjectId: detail.value.denglmbmobjectid || detail.value.enterpriseObjectID,
        taxNo: detail.value.unifiedSocialCreditCode,
        transactorMobile: detail.value.phonenumber,

    }
    mutate(params, {
        onSuccess: () => {
            ElMessage.success('操作成功')
        },
    })
}

async function getData() {
    getDetail()
}
function getDetail() {
    getNewCompanyOrgDetail(showId.value).then((res: any) => {
        if (res.code === 200) {
            detail.value = res.data
            isLoading.value = false
            getSubData()
        }
        else {
            isLoading.value = false
        }
    })
}

watch(showId, (val: any) => {
    if (val) {
        getData()
    }
}, {
    deep: true,
    immediate: true,
})
</script>

<template>
    <ElCard class="mb-20">
        <ElRow class="flex justify-between">
            <ElButton @click="goToList">
                返回列表
            </ElButton>

            <ElButton v-if="!isLoading && detail.contractFlag === 1 && detail.contractPlat === 2"
                      type="primary"
                      :disabled="isPending"
                      @click="emitEAuth"
            >
                发送e签宝授权链接
            </ElButton>
        </ElRow>

        <div class="info-title">
            企业注册信息
        </div>

        <el-skeleton v-if="isLoading"
                     animated
        />

        <ElForm v-else
                :model="detail"
                label-width="auto"
        >
            <ElRow :gutter="20">
                <ElCol :span="8">
                    <ElFormItem label="企业号:">
                        {{ detail.enterpriseId }}
                    </ElFormItem>
                </ElCol>

                <ElCol :span="8">
                    <ElFormItem label="企业名称:">
                        {{ detail.enterpriseName }}
                    </ElFormItem>
                </ElCol>

                <ElCol :span="8">
                    <ElFormItem label="所属城市:">
                        {{ detail.areaName }}
                    </ElFormItem>
                </ElCol>

                <ElCol :span="8">
                    <ElFormItem label="企业简称:">
                        {{ detail.enterpriseShort }}
                    </ElFormItem>
                </ElCol>
            </ElRow>

            <ElRow :gutter="20">
                <ElCol :span="8">
                    <ElFormItem label="统一社会信用代码:">
                        {{ detail.unifiedSocialCreditCode }}
                    </ElFormItem>
                </ElCol>

                <ElCol :span="8">
                    <ElFormItem label="企业联系电话:">
                        {{ detail.registeredMobile }}
                    </ElFormItem>
                </ElCol>
            </ElRow>

            <ElRow :gutter="20">
                <ElCol :span="8">
                    <ElFormItem label="企业级别:">
                        <ElTag :type=" detail?.enterpriseLevelId === '1' ? 'warning' : 'success'">
                            {{ detail.enterpriseLevel }}
                        </ElTag>
                    </ElFormItem>
                </ElCol>

                <ElCol v-if="detail?.enterpriseLevelId === '2'"
                       :span="8"
                >
                    <ElFormItem label="所属上级企业:">
                        {{ detail.parentName }}
                    </ElFormItem>
                </ElCol>
            </ElRow>

            <ElRow :gutter="20">
                <ElCol :span="8">
                    <ElFormItem label="企业类型:">
                        {{ detail.enterpriseTypeName }}
                    </ElFormItem>
                </ElCol>

                <ElCol :span="8">
                    <ElFormItem label="业务类别:">
                        {{ detail.catType }}
                    </ElFormItem>
                </ElCol>

                <ElCol :span="8">
                    <ElFormItem label="合作类型:">
                        {{ useDict('CooperationType', detail.cooperationType) }}
                    </ElFormItem>
                </ElCol>
            </ElRow>

            <ElRow :gutter="20">
                <ElCol :span="8">
                    <ElFormItem label="注册日期:">
                        {{ detail.establishmenDate?.split('T')[0] || '' }}
                    </ElFormItem>
                </ElCol>

                <ElCol :span="8">
                    <ElFormItem label="企业法人:">
                        {{ detail.legalRepresentative }}
                    </ElFormItem>
                </ElCol>

                <ElCol :span="8">
                    <ElFormItem label="法人证件号码:">
                        {{ useAesDecrypt(detail.legalCard) }}
                    </ElFormItem>
                </ElCol>
            </ElRow>

            <ElRow :gutter="20">
                <ElCol :span="8">
                    <ElFormItem label="营业执照:">
                        <el-image v-if="detail.businessLicense"
                                  class="box"
                                  :src="detail.businessLicense"
                                  :preview-src-list="[detail.businessLicense]"
                                  fit="contain"
                        />

                        <div v-else
                             class="box"
                        />
                    </ElFormItem>
                </ElCol>

                <ElCol :span="8">
                    <ElFormItem label="企业法人身份证(正面):">
                        <el-image v-if="detail.legalCardFront"
                                  class="box"
                                  :src="detail.legalCardFront"
                                  :preview-src-list="[detail.legalCardFront]"
                                  fit="contain"
                        />

                        <div v-else
                             class="box"
                        />
                    </ElFormItem>
                </ElCol>

                <ElCol :span="8">
                    <ElFormItem label="企业法人身份证(反面):">
                        <el-image v-if="detail.legalCardBack"
                                  class="box"
                                  :src="detail.legalCardBack"
                                  :preview-src-list="[detail.legalCardBack]"
                                  fit="contain"
                        />

                        <div v-else
                             class="box"
                        />
                    </ElFormItem>
                </ElCol>
            </ElRow>

            <ElFormItem label="企业注册地址:">
                {{ detail.registeredAddress }}
            </ElFormItem>

            <ElFormItem label="企业状态:">
                {{ useDict('EnterpriseStatus', detail.status) }}
            </ElFormItem>

            <ElRow :gutter="20">
                <ElCol :span="8">
                    <ElFormItem label="是否开通电子签:">
                        {{ detail.contractFlag === 1 ? '是' : '否' }}
                    </ElFormItem>
                </ElCol>

                <ElCol :span="8">
                    <ElFormItem label="电子签:">
                        {{ detail.contractPlat === 1 ? '诺诺' : 'e签宝' }}
                    </ElFormItem>
                </ElCol>
            </ElRow>

            <div class="info-title">
                企业管理员信息
            </div>

            <ElRow :gutter="20">
                <ElCol :span="8">
                    <ElFormItem label="企业管理员账号:">
                        {{ detail.enterpriseAccount }}
                    </ElFormItem>
                </ElCol>

                <ElCol :span="8">
                    <ElFormItem label="姓名:">
                        {{ detail.userName }}
                    </ElFormItem>
                </ElCol>

                <ElCol :span="8">
                    <ElFormItem label="身份证号:">
                        {{ useAesDecrypt(detail.idCard) }}
                    </ElFormItem>
                </ElCol>
            </ElRow>

            <ElRow :gutter="20">
                <ElCol :span="8">
                    <ElFormItem label="手机号:">
                        {{ useAesDecrypt(detail.phonenumber) }}
                    </ElFormItem>
                </ElCol>

                <ElCol :span="8">
                    <ElFormItem label="邮箱:">
                        {{ detail.email }}
                    </ElFormItem>
                </ElCol>
            </ElRow>
        </ElForm>

        <template v-if="detail?.enterpriseLevelId === '1'">
            <div class="info-title">
                二级企业
            </div>

            <!-- 列表 -->
            <vxe-grid ref="xGrid"
                      v-bind="gridOptions"
                      v-on="gridEvents"
            >
                <template #enterpriseLevelId="{ row }">
                    <div class="flex gap-2">
                        <ElTag :type=" row?.enterpriseLevelId === '1' ? 'warning' : 'success'">
                            {{ row.enterpriseLevel }}
                        </ElTag>
                    </div>
                </template>

                <template #status="{ row }">
                    {{ useDict('EnterpriseStatus', row.status) }}
                </template>

                <template #cooperationType="{ row }">
                    {{ useDict('CooperationType', row.cooperationType) }}
                </template>

                <template #createTime="{ row }">
                    {{ row.createTime }}
                </template>

                <template #operate="{ row }">
                    <ButtonItem :btns="btns"
                                @btn-click="doAction($event, row)"
                    />
                </template>
            </vxe-grid>
        </template>

        <div style="text-align: center;margin-top: 20px;">
            <ElButton type="primary"
                      @click="onSubmit"
            >
                编辑
            </ElButton>

            <ElButton @click="goToList">
                返回列表
            </ElButton>
        </div>
    </ElCard>

    <viewItem v-model="show"
              :data="subData"
    />
</template>

<style lang="less" scoped>
.info-title {
    font-size: 16px;
    font-weight: 600;
    line-height: 60px;
}
.box {
    width: 120px;
    height: 120px;
}
</style>
